import { defineStore } from "pinia";
import _ from "lodash";
import { menus } from "@/utils/menus.js";
import { filterMenuBySelectedKeys } from "@/utils/menuUtils.js";

export const useMainStore = defineStore("main", {
  state: () => {
    return { _user: null, _token: null, _menus: [] };
  },
  // 所有数据持久化
  // persist: true,
  // 持久化存储插件其他配置
  persist: {
    // 修改存储中使用的键名称，默认为当前 Store的 id
    key: "arrowkey",
    // 修改为 sessionStorage，默认为 localStorage
    storage: window.sessionStorage,
  },
  getters: {
    user(state) {
      return state._user;
    },
    menus(state) {
      return state._menus;
    },
  },
  actions: {
    async login(obj) {
      const res = await this.$http.post("/account/login", obj);
      const { success, data, msg } = res || {};
      let menuArray = [];
      if (success) {
        this._user = data.user;
        this._token = data.token;
        // if (data.user.role === "admin") {
        //   menuArray = menus;
        // } else {
        //   menuArray = _.filter(menus, (o) => o.label != "信息管理");
        // }
        if (data.user.role === "admin") {
          menuArray = menus; // 管理员：所有菜单
        } else {
          // 非管理员：根据 workFlows 权限提取菜单
          const userWorkFlows = JSON.parse(data.user.menus);
          console.log('用户权限 workFlows:', userWorkFlows); // 确认格式

          if (Array.isArray(userWorkFlows) && userWorkFlows.length > 0) {
            menuArray = filterMenuBySelectedKeys(menus,userWorkFlows);
          } else {
            menuArray = [];
          }
        }
      }
      console.log("menuArray",JSON.stringify(menuArray))
      this._menus = menuArray;
      return { success, data: menuArray };
    },
    loginOut() {
      this._user = null;
      this._token = null;
    },
    setUser(obj) {
      this._user = obj;
    },
  },
});
